package com.xs.ahoi.hcxs.ui.dialog;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.google.common.collect.Maps;
import com.xs.ahoi.hcxs.Ahoi;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.model.IdName;
import com.xs.ahoi.hcxs.model.enums.SpeakerEnum;
import com.xs.ahoi.hcxs.model.enums.SpeedEnum;
import com.xs.ahoi.hcxs.service.BGMService;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.FileUtil;
import com.xs.ahoi.hcxs.utils.MeasureUtil;
import com.xs.ahoi.hcxs.utils.ObjectUtils;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;

import org.apache.commons.compress.utils.Lists;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnItemClick;


/**
 * 发音人选择弹窗
 *
 * @author: fuhuichao
 * @date: 2022/5/10 4:23 下午
 */
public class DialogSpeaker extends BaseDialog {

    @BindView(R.id.lvSpeakerList)
    public ListView lvSpeakerList;
    @BindView(R.id.tvSpeedAdd)
    public TextView tvSpeedAdd;
    @BindView(R.id.tvSpeedSub)
    public TextView tvSpeedSub;
    @BindView(R.id.tvSpeedText)
    public TextView tvSpeedText;

    private ConfigDao configDao;
    private List<Map<String, Object>> datas;
    private Map<String, Object> oneData;
    private DataAdapter adapter;

    // tts语速
    private int ttsSpeed;

    public DialogSpeaker(@NonNull Context context) {
        super(context, R.style.common_dialog);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_speaker;
    }

    @Override
    protected int showPosition() {
        return Gravity.CENTER;
    }

    // 初始化
    @Override
    protected void initData() {
        configDao = ConfigDao.getInstance();

        // 显示已配置的语速
        ttsSpeed = configDao.getTtsSpeed();
        tvSpeedText.setText(SpeedEnum.getByCode(ttsSpeed).getText());

        // 获取缓存中保存的speaker
        int ttsSpeaker = configDao.getTtsSpeaker();

        // 初始化列表数据
        datas = Lists.newArrayList();
        for (SpeakerEnum item : SpeakerEnum.values()) {
            oneData = Maps.newHashMap();
            oneData.put("id", item.getCode());
            oneData.put("name", item.getText());
            oneData.put("select", 0);
            if (ttsSpeaker == item.getCode()) {
                oneData.put("select", 1);
            }
            datas.add(oneData);
        }

        // 绑定adapter
        adapter = new DataAdapter(getContext(), datas, R.layout.listview_item_dialog_speaker, new String[]{"name"}, new int[]{R.id.tvName});
        lvSpeakerList.setAdapter(adapter);

        // 设置listview的高度，进而限制弹窗高度不超过屏幕高度的75%
        ViewGroup.LayoutParams layoutParams = lvSpeakerList.getLayoutParams();
        int windowHeight = MeasureUtil.getScreenHeight(Ahoi.getInstance().getActivity());
        int maxHeight = (int) (windowHeight * 0.75 - 600);
        View v = adapter.getView(0, null, lvSpeakerList);
        v.measure(0, 0);
        int itemHeight = v.getMeasuredHeight();
        if (SpeakerEnum.values().length * itemHeight > maxHeight) {
            layoutParams.height = maxHeight;
            lvSpeakerList.setLayoutParams(layoutParams);
        }
    }

    @OnItemClick({R.id.lvSpeakerList})
    public void onItemClick(int position) {
        // 获取点击项
        Map<String, Object> map;
        for (int i = 0; i < datas.size(); i++) {
            map = datas.get(i);
            map.put("select", 0);
            if (i == position) {
                map.put("select", 1);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @OnClick({R.id.tvDialogOk, R.id.tvDialogCancel, R.id.tvSpeedAdd, R.id.tvSpeedSub})
    public void onClick(View v) {
        switch (v.getId()) {
            // 确认
            case R.id.tvDialogOk:
                change();
                super.dismiss();
                break;
            // 取消
            case R.id.tvDialogCancel:
                super.dismiss();
                break;
            // 语速+
            case R.id.tvSpeedAdd:
                ttsSpeed = SpeedEnum.getNextSpeed(ttsSpeed, true).getCode();
                updateTtsShowText();
                break;
            // 语速-
            case R.id.tvSpeedSub:
                ttsSpeed = SpeedEnum.getNextSpeed(ttsSpeed, false).getCode();
                updateTtsShowText();
                break;
        }
    }

    /**
     * 展示TTS语速文本
     */
    private void updateTtsShowText() {
        tvSpeedText.setText(SpeedEnum.getByCode(ttsSpeed).getText());
    }

    // 获取选中的项
    private String getSelectedItem() {
        Map<String, Object> map;
        for (int i = 0; i < datas.size(); i++) {
            map = datas.get(i);
            if (ObjectUtils.toInteger(map.get("select")) == 1) {
                return map.get("name").toString();
            }
        }
        return "null";
    }

    // 改变结果
    private void change() {
        String selectedName = getSelectedItem();
        SpeakerEnum speakerEnum = SpeakerEnum.getByText(selectedName);
        configDao.setTtsSpeaker(speakerEnum.getCode());
        configDao.setTtsSpeed(ttsSpeed);

        // 更新tts
        TtsUtil.getInstance().changeTtsParam();
        if (BookFactory.getInstance().isPlaying()) {
            TtsUtil.getInstance().stop();
            TtsUtil.getInstance().start();
        }
    }

    // seekbar监听
//    SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() {
//        @Override
//        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//            bgmControl.changeV(progress);
//            configDao.setBgmV(progress);
//        }
//
//        @Override
//        public void onStartTrackingTouch(SeekBar seekBar) {
//
//        }
//
//        @Override
//        public void onStopTrackingTouch(SeekBar seekBar) {
//        }
//    };


    //**********************************************************
    //********************get set 方法**************************
    //**********************************************************

    // 自定义SimpleAdapter
    private class DataAdapter extends SimpleAdapter {

        private DataAdapter(Context context, List<? extends Map<String, Object>> datas, int resource, String[] from, int[] to) {
            super(context, datas, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            // 将已选中的编码设置为红色
            Map<String, Object> data = getItem(position);
            TextView tvName = view.findViewById(R.id.tvName);
            ImageView ivCheck = view.findViewById(R.id.ivCheck);
            if (ObjectUtils.toInteger(data.get("select")) == 1) {
                tvName.setTextColor(ContextCompat.getColor(getContext(), R.color.colorRed));
                ivCheck.setVisibility(View.VISIBLE);
            } else {
                tvName.setTextColor(ContextCompat.getColor(getContext(), R.color.colorBlack));
                ivCheck.setVisibility(View.GONE);
            }
            return view;
        }

        @Override
        public Map<String, Object> getItem(int position) {
            return datas.get(position);
        }
    }
}
